﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Tracing;
using Yitter.IdGenerator;

namespace Admin.NET.Application;
 
/// <summary>
/// 工单管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
[EventData]
public class ticketsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<tickets> _ticketsRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;
    private readonly SqlSugarRepository<stocklist> _stocklistRep;

    public ticketsService(SqlSugarRepository<tickets> ticketsRep, SqlSugarRepository<stocklist> stocklistRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _stocklistRep = stocklistRep;
        _ticketsRep = ticketsRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询工单管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询工单管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ticketsOutput>> Page(PageticketsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _ticketsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ticketstype.Contains(input.Keyword) || u.progress.Contains(input.Keyword) || u.source.Contains(input.Keyword) || u.sourceticketnumber.Contains(input.Keyword) || u.remark.Contains(input.Keyword) || u.encode.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ticketstype), u => u.ticketstype.Contains(input.ticketstype.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.progress), u => u.progress.Contains(input.progress.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.source), u => u.source.Contains(input.source.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.sourceticketnumber), u => u.sourceticketnumber.Contains(input.sourceticketnumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.remark), u => u.remark.Contains(input.remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.encode), u => u.encode.Contains(input.encode.Trim()))
            .WhereIF(input.masterId != null, u => u.masterId == input.masterId)
            .WhereIF(input.productionId != null, u => u.productionId == input.productionId)
            .WhereIF(input.quantity != null, u => u.quantity == input.quantity)
            .WhereIF(input.completedquantity != null, u => u.completedquantity == input.completedquantity)
            .WhereIF(input.planstarttimeRange?.Length == 2, u => u.planstarttime >= input.planstarttimeRange[0] && u.planstarttime <= input.planstarttimeRange[1])
            .WhereIF(input.planEndtimeRange?.Length == 2, u => u.planEndtime >= input.planEndtimeRange[0] && u.planEndtime <= input.planEndtimeRange[1])
            .WhereIF(input.actualstarttimeRange?.Length == 2, u => u.actualstarttime >= input.actualstarttimeRange[0] && u.actualstarttime <= input.actualstarttimeRange[1])
            .WhereIF(input.actualendtimeRange?.Length == 2, u => u.actualendtime >= input.actualendtimeRange[0] && u.actualendtime <= input.actualendtimeRange[1])
            .WhereIF(input.inputquantity != null, u => u.inputquantity == input.inputquantity)
            .WhereIF(input.goodproductquantity != null, u => u.goodproductquantity == input.goodproductquantity)
            .WhereIF(input.scrapquantity != null, u => u.scrapquantity == input.scrapquantity)
            .WhereIF(input.processprogress != null, u => u.processprogress == input.processprogress)
            .LeftJoin<Partnum>((u, master) => u.masterId == master.Id)
            .LeftJoin<production>((u, master, production) => u.productionId == production.Id)
            .LeftJoin<Routing>((u, master, production, processprogress) => u.processprogress == processprogress.Id)
            .Select((u, master, production, processprogress) => new ticketsOutput
            {
                Id = u.Id,
                ticketstype = u.ticketstype,
                masterId = u.masterId,
                masterFkDisplayName = $"{master.PartNumCoding}",
                productionId = u.productionId,
                productionFkDisplayName = $"{production.ProductionName}",
                ticketsstates = u.ticketsstates,
                quantity = u.quantity,
                completedquantity = u.completedquantity,
                progress = u.progress,
                planstarttime = u.planstarttime,
                planEndtime = u.planEndtime,
                actualstarttime = u.actualstarttime,
                actualendtime = u.actualendtime,
                inputquantity = u.inputquantity,
                goodproductquantity = u.goodproductquantity,
                scrapquantity = u.scrapquantity,
                source = u.source,
                sourceticketnumber = u.sourceticketnumber,
                remark = u.remark,
                skipornot = u.skipornot,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                processprogress = u.processprogress,
                processprogressFkDisplayName = $"{processprogress.routingname}",
                encode = u.encode,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取工单管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取工单管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<tickets> Detail([FromQuery] QueryByIdticketsInput input)
    {
        return await _ticketsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加工单管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加工单管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]

    public async Task<long> Add(AddticketsInput input)
    {
        var IDDD = YitIdHelper.NextId().ToString();

        var entity = input.Adapt<tickets>();
        entity.Id = Convert.ToInt64(IDDD);
        entity.completedquantity = 0;
        entity.progress = "0%";
        entity.inputquantity = 0;
        entity.goodproductquantity = 0;
        entity.scrapquantity = 0;
        entity.source = "MES";
     



        stocklist stocklist= new stocklist();

        stocklist.workordernum =Convert.ToInt64( IDDD);
        stocklist.states = false;

        stocklist.oddnumber = YitIdHelper.NextId().ToString();
      var data=  await _stocklistRep.InsertAsync(stocklist) ? stocklist.Id : 0;
        return await _ticketsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新工单管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新工单管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateticketsInput input)
    {
        var entity = input.Adapt<tickets>();
        await _ticketsRep.AsUpdateable(entity)
        .IgnoreColumns(u => new {
            u.ticketsstates,
            u.completedquantity,
            u.progress,
            u.actualstarttime,
            u.actualendtime,
            u.inputquantity,
            u.goodproductquantity,
            u.scrapquantity,
            u.source,
            u.sourceticketnumber,
        })
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除工单管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除工单管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteticketsInput input)
    {
        var entity = await _ticketsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _ticketsRep.FakeDeleteAsync(entity);   //假删除
        //await _ticketsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除工单管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除工单管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteticketsInput> input)
    {
        var exp = Expressionable.Create<tickets>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _ticketsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _ticketsRep.FakeDeleteAsync(list);   //假删除
        //return await _ticketsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataticketsInput input)
    {
        var masterIdData = await _ticketsRep.Context.Queryable<Partnum>()
            .InnerJoinIF<tickets>(input.FromPage, (u, r) => u.Id == r.masterId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}"
            }).ToListAsync();
        var productionIdData = await _ticketsRep.Context.Queryable<production>()
            .InnerJoinIF<tickets>(input.FromPage, (u, r) => u.Id == r.productionId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ProductionName}"
            }).ToListAsync();
        var processprogressData = await _ticketsRep.Context.Queryable<Routing>()
            .InnerJoinIF<tickets>(input.FromPage, (u, r) => u.Id == r.processprogress)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.routingname}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "masterId", masterIdData },
            { "productionId", productionIdData },
            { "processprogress", processprogressData },
        };
    }
    
    /// <summary>
    /// 导出工单管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出工单管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageticketsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportticketsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var ticketstypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "work _order _type" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.ticketstypeDictLabel = ticketstypeDictMap.GetValueOrDefault(e.ticketstype ?? "", e.ticketstype);
        });
        return ExcelHelper.ExportTemplate(list, "工单管理导出记录");
    }
    
    /// <summary>
    /// 下载工单管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载工单管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportticketsOutput>(), "工单管理导入模板", (_, info) =>
        {
            if (nameof(ExportticketsOutput.masterFkDisplayName) == info.Name) return _ticketsRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}").Distinct().ToList();
            if (nameof(ExportticketsOutput.productionFkDisplayName) == info.Name) return _ticketsRep.Context.Queryable<production>().Select(u => $"{u.ProductionName}").Distinct().ToList();
            if (nameof(ExportticketsOutput.processprogressFkDisplayName) == info.Name) return _ticketsRep.Context.Queryable<Routing>().Select(u => $"{u.routingname}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入工单管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入工单管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var ticketstypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "work _order _type" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportticketsInput, tickets>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 产品主数据
                    var masterIdLabelList = pageItems.Where(x => x.masterFkDisplayName != null).Select(x => x.masterFkDisplayName).Distinct().ToList();
                    if (masterIdLabelList.Any()) {
                        var masterIdLinkMap = _ticketsRep.Context.Queryable<Partnum>().Where(u => masterIdLabelList.Contains($"{u.PartNumCoding}")).ToList().ToDictionary(u => $"{u.PartNumCoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.masterId = masterIdLinkMap.GetValueOrDefault(e.masterFkDisplayName ?? "");
                            if (e.masterId == null) e.Error = "产品主数据链接失败";
                        });
                    }
                    // 链接 产线
                    var productionIdLabelList = pageItems.Where(x => x.productionFkDisplayName != null).Select(x => x.productionFkDisplayName).Distinct().ToList();
                    if (productionIdLabelList.Any()) {
                        var productionIdLinkMap = _ticketsRep.Context.Queryable<production>().Where(u => productionIdLabelList.Contains($"{u.ProductionName}")).ToList().ToDictionary(u => $"{u.ProductionName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.productionId = productionIdLinkMap.GetValueOrDefault(e.productionFkDisplayName ?? "");
                            if (e.productionId == null) e.Error = "产线链接失败";
                        });
                    }
                    // 链接 工序进度
                    var processprogressLabelList = pageItems.Where(x => x.processprogressFkDisplayName != null).Select(x => x.processprogressFkDisplayName).Distinct().ToList();
                    if (processprogressLabelList.Any()) {
                        var processprogressLinkMap = _ticketsRep.Context.Queryable<Routing>().Where(u => processprogressLabelList.Contains($"{u.routingname}")).ToList().ToDictionary(u => $"{u.routingname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.processprogress = processprogressLinkMap.GetValueOrDefault(e.processprogressFkDisplayName ?? "");
                            if (e.processprogress == null) e.Error = "工序进度链接失败";
                        });
                    }
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.ticketstypeDictLabel)) continue;
                        item.ticketstype = ticketstypeDictMap.GetValueOrDefault(item.ticketstypeDictLabel);
                        if (item.ticketstype == null) item.Error = "类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<tickets>>();
                    
                    var storageable = _ticketsRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ticketstype?.Length > 32, "类型长度不能超过32个字符")
                        .SplitError(it => it.Item.progress?.Length > 32, "进度长度不能超过32个字符")
                        .SplitError(it => it.Item.source?.Length > 32, "来源长度不能超过32个字符")
                        .SplitError(it => it.Item.sourceticketnumber?.Length > 32, "源工单号长度不能超过32个字符")
                        .SplitError(it => it.Item.remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.encode?.Length > 100, "编码长度不能超过100个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
